// 肉鸽整合系统 - 协调所有增强功能的前10关卡优化
class RoguelikeIntegration {
    constructor() {
        this.initialized = false;
        this.levelEnhancements = {};
        this.currentEnhancements = [];
        
        // 关卡特定的肉鸽配置
        this.levelConfigs = this.initializeLevelConfigs();
        
        // 监听游戏事件
        this.setupEventListeners();
        
        // 初始化延迟
        setTimeout(() => {
            this.initialize();
        }, 1000);
    }
    
    initialize() {
        if (this.initialized) return;
        
        try {
            // 确保所有系统都已加载
            this.checkSystemAvailability();
            
            // 初始化系统集成
            this.initializeSystemIntegration();
            
            // 设置关卡间肉鸽循环
            this.setupRoguelikeLoop();
            
            // 增强现有游戏事件
            this.enhanceGameEvents();
            
            this.initialized = true;
            console.log('🎮 肉鸽整合系统初始化完成');
            
        } catch (error) {
            console.error('肉鸽整合系统初始化失败:', error);
        }
    }
    
    initializeLevelConfigs() {
        return {
            1: {
                name: '教学楼入口',
                roguelikeFeatures: ['基础升级选择'],
                specialEvents: ['新手指导事件'],
                equipmentDropRate: 0.3,
                modifierChance: 0.2,
                description: '学习基本肉鸽机制'
            },
            2: {
                name: '学校走廊',
                roguelikeFeatures: ['装备掉落', '随机修饰符'],
                specialEvents: ['武器箱发现'],
                equipmentDropRate: 0.4,
                modifierChance: 0.3,
                description: '开始体验程序化内容'
            },
            3: {
                name: '图书馆惊魂',
                roguelikeFeatures: ['特殊区域', '随机事件'],
                specialEvents: ['神秘商人', '知识之力'],
                equipmentDropRate: 0.5,
                modifierChance: 0.4,
                description: '引入环境交互和选择'
            },
            4: {
                name: '化学实验室',
                roguelikeFeatures: ['实验室事件', '风险收益选择'],
                specialEvents: ['奇怪的实验', '化学反应'],
                equipmentDropRate: 0.6,
                modifierChance: 0.5,
                description: '风险与收益的平衡'
            },
            5: {
                name: '学校食堂',
                roguelikeFeatures: ['大型战斗', '多重选择'],
                specialEvents: ['食物补给', '群体战术'],
                equipmentDropRate: 0.7,
                modifierChance: 0.6,
                description: '中期挑战和策略选择'
            },
            6: {
                name: '体育馆血战',
                roguelikeFeatures: ['竞技场模式', '精英敌人'],
                specialEvents: ['竞技挑战', '荣誉奖励'],
                equipmentDropRate: 0.8,
                modifierChance: 0.7,
                description: '技能考验和装备升级'
            },
            7: {
                name: '宿舍楼围困',
                roguelikeFeatures: ['多层建筑', '连续战斗'],
                specialEvents: ['生存挑战', '资源管理'],
                equipmentDropRate: 0.9,
                modifierChance: 0.8,
                description: '持续压力和资源管理'
            },
            8: {
                name: '天台最后防线',
                roguelikeFeatures: ['防御战', '波次挑战'],
                specialEvents: ['最后防线', '英雄时刻'],
                equipmentDropRate: 1.0,
                modifierChance: 0.9,
                description: '高强度生存挑战'
            },
            9: {
                name: '地下室深渊',
                roguelikeFeatures: ['黑暗探索', '恐怖元素'],
                specialEvents: ['深渊凝视', '暗影交易'],
                equipmentDropRate: 1.2,
                modifierChance: 1.0,
                description: '极限挑战和心理压力'
            },
            10: {
                name: '校长室终极对决',
                roguelikeFeatures: ['BOSS战', '终极奖励'],
                specialEvents: ['终极对决', '胜利加冕'],
                equipmentDropRate: 1.5,
                modifierChance: 1.0,
                description: '最终考验和荣耀时刻'
            }
        };
    }
    
    checkSystemAvailability() {
        const requiredSystems = [
            'roguelikeSystem',
            'roguelikeEnhanced', 
            'equipmentSystem'
        ];
        
        const missingSystems = requiredSystems.filter(system => !window[system]);
        
        if (missingSystems.length > 0) {
            console.warn('缺少必要系统:', missingSystems);
        }
        
        console.log('系统可用性检查完成');
    }
    
    initializeSystemIntegration() {
        // 扩展现有的关卡管理器
        if (window.LevelManager && !window.LevelManager.prototype.roguelikeEnhanced) {
            this.enhanceLevelManager();
        }
        
        // 扩展游戏引擎
        if (window.GameEngine && !window.GameEngine.prototype.roguelikeEnhanced) {
            this.enhanceGameEngine();
        }
        
        // 设置装备系统集成
        this.setupEquipmentIntegration();
    }
    
    enhanceLevelManager() {
        const originalStartLevel = window.LevelManager.prototype.startLevel;
        
        window.LevelManager.prototype.startLevel = function(levelNumber) {
            // 调用原始方法
            const result = originalStartLevel.call(this, levelNumber);
            
            // 应用肉鸽增强
            if (window.roguelikeIntegration) {
                window.roguelikeIntegration.enhanceLevel(levelNumber);
            }
            
            return result;
        };
        
        // 标记已增强
        window.LevelManager.prototype.roguelikeEnhanced = true;
        console.log('关卡管理器已增强');
    }
    
    enhanceGameEngine() {
        const originalUpdate = window.GameEngine.prototype.update;
        
        window.GameEngine.prototype.update = function(currentTime) {
            // 调用原始更新
            if (originalUpdate) {
                originalUpdate.call(this, currentTime);
            }
            
            // 更新肉鸽系统
            if (window.roguelikeIntegration && this.gameState === 'playing') {
                window.roguelikeIntegration.updateRoguelikeElements();
            }
        };
        
        // 标记已增强
        window.GameEngine.prototype.roguelikeEnhanced = true;
        console.log('游戏引擎已增强');
    }
    
    setupEquipmentIntegration() {
        // 替换原有的武器生成逻辑
        if (window.WeaponSpawner) {
            const originalSpawnWeapon = window.WeaponSpawner.prototype.spawnRandomWeapon;
            
            window.WeaponSpawner.prototype.spawnRandomWeapon = function(x, y) {
                // 使用新的装备系统
                if (window.equipmentSystem && Math.random() < 0.7) {
                    const rarity = this.selectWeaponRarity();
                    window.equipmentSystem.spawnEquipmentDrop(x, y, 'weapon', rarity);
                } else if (originalSpawnWeapon) {
                    originalSpawnWeapon.call(this, x, y);
                }
            };
            
            // 添加稀有度选择方法
            window.WeaponSpawner.prototype.selectWeaponRarity = function() {
                const rand = Math.random();
                if (rand < 0.05) return 'legendary';
                if (rand < 0.15) return 'epic';
                if (rand < 0.35) return 'rare';
                return 'common';
            };
        }
    }
    
    enhanceLevel(levelNumber) {
        const config = this.levelConfigs[levelNumber];
        if (!config) return;
        
        console.log(`🎯 应用关卡 ${levelNumber} 肉鸽增强:`, config.name);
        
        // 应用关卡特定配置
        this.applyLevelConfiguration(levelNumber, config);
        
        // 生成程序化内容
        this.generateProceduralContent(levelNumber, config);
        
        // 设置特殊事件
        this.setupLevelEvents(levelNumber, config);
        
        // 调整难度和奖励
        this.adjustLevelBalance(levelNumber, config);
    }
    
    applyLevelConfiguration(levelNumber, config) {
        // 设置装备掉落率
        if (window.gameEngine) {
            window.gameEngine.equipmentDropRate = config.equipmentDropRate;
        }
        
        // 设置修饰符出现几率
        if (window.levelManager && window.levelManager.levelModifierSystem) {
            window.levelManager.levelModifierSystem.modifierChance = config.modifierChance;
        }
        
        // 显示关卡特色提示
        this.showLevelFeatureHint(config);
    }
    
    generateProceduralContent(levelNumber, config) {
        // 生成程序化装备掉落
        this.scheduleEquipmentDrops(levelNumber, config);
        
        // 生成随机道具
        this.scheduleItemDrops(levelNumber, config);
        
        // 应用关卡修饰符
        this.applyLevelModifiers(levelNumber, config);
    }
    
    scheduleEquipmentDrops(levelNumber, config) {
        const dropCount = Math.floor(2 + levelNumber * 0.3);
        
        for (let i = 0; i < dropCount; i++) {
            setTimeout(() => {
                if (window.equipmentSystem && window.gameEngine) {
                    const x = Math.random() * 900 + 50;
                    const y = Math.random() * 650 + 50;
                    
                    // 根据关卡调整稀有度
                    let rarity = 'common';
                    const rand = Math.random();
                    
                    if (levelNumber >= 7) {
                        if (rand < 0.1) rarity = 'legendary';
                        else if (rand < 0.3) rarity = 'epic';
                        else if (rand < 0.6) rarity = 'rare';
                    } else if (levelNumber >= 4) {
                        if (rand < 0.05) rarity = 'epic';
                        else if (rand < 0.25) rarity = 'rare';
                    } else if (levelNumber >= 2) {
                        if (rand < 0.15) rarity = 'rare';
                    }
                    
                    window.equipmentSystem.spawnEquipmentDrop(x, y, null, rarity);
                }
            }, Math.random() * 30000 + 5000); // 5-35秒内随机掉落
        }
    }
    
    scheduleItemDrops(levelNumber, config) {
        const itemCount = Math.floor(1 + levelNumber * 0.2);
        
        for (let i = 0; i < itemCount; i++) {
            setTimeout(() => {
                if (window.equipmentSystem && window.gameEngine) {
                    const x = Math.random() * 900 + 50;
                    const y = Math.random() * 650 + 50;
                    
                    let rarity = 'common';
                    if (levelNumber >= 5) {
                        const rand = Math.random();
                        if (rand < 0.1) rarity = 'epic';
                        else if (rand < 0.3) rarity = 'rare';
                    }
                    
                    window.equipmentSystem.spawnEquipmentDrop(x, y, 'item', rarity);
                }
            }, Math.random() * 40000 + 10000); // 10-50秒内随机掉落
        }
    }
    
    applyLevelModifiers(levelNumber, config) {
        if (!window.roguelikeEnhanced || !window.roguelikeEnhanced.levelGenerator) return;
        
        // 为高级关卡应用更多修饰符
        if (levelNumber >= 3 && Math.random() < config.modifierChance) {
            const variant = window.roguelikeEnhanced.levelGenerator.generateLevelVariant(levelNumber - 1);
            const modifiedVariant = window.roguelikeEnhanced.levelGenerator.applyRandomModifiers(variant);
            
            if (modifiedVariant.modifiers && modifiedVariant.modifiers.length > 0) {
                this.displayLevelModifiers(modifiedVariant.modifiers);
            }
        }
    }
    
    setupLevelEvents(levelNumber, config) {
        // 为特定关卡设置特殊事件
        config.specialEvents.forEach((eventType, index) => {
            setTimeout(() => {
                this.triggerSpecialEvent(eventType, levelNumber);
            }, (index + 1) * 20000); // 每20秒触发一个事件
        });
    }
    
    triggerSpecialEvent(eventType, levelNumber) {
        switch (eventType) {
            case '新手指导事件':
                this.showTutorialEvent();
                break;
            case '武器箱发现':
                this.spawnWeaponCache();
                break;
            case '神秘商人':
                if (window.roguelikeEnhanced && window.roguelikeEnhanced.eventSystem) {
                    const event = window.roguelikeEnhanced.eventSystem.events.find(e => e.id === 'mysteriousTrader');
                    if (event) {
                        window.roguelikeEnhanced.showEventInterface(event);
                    }
                }
                break;
            case '奇怪的实验':
                if (window.roguelikeEnhanced && window.roguelikeEnhanced.eventSystem) {
                    const event = window.roguelikeEnhanced.eventSystem.events.find(e => e.id === 'strangeExperiment');
                    if (event) {
                        window.roguelikeEnhanced.showEventInterface(event);
                    }
                }
                break;
            default:
                this.showGenericEvent(eventType, levelNumber);
                break;
        }
    }
    
    showTutorialEvent() {
        this.showEventNotification(
            '📚 新手指导',
            '欢迎来到肉鸽模式！每次游戏都会有不同的体验。击败敌人获得升级，死亡后保留部分进度。',
            '#4CAF50'
        );
    }
    
    spawnWeaponCache() {
        if (window.equipmentSystem && window.gameEngine) {
            const x = Math.random() * 800 + 100;
            const y = Math.random() * 600 + 100;
            
            // 生成3个武器
            for (let i = 0; i < 3; i++) {
                window.equipmentSystem.spawnEquipmentDrop(
                    x + (i - 1) * 40, 
                    y + (i - 1) * 20, 
                    'weapon', 
                    'rare'
                );
            }
            
            this.showEventNotification(
                '📦 武器缓存',
                '发现了一个武器缓存！里面有多把稀有武器等待你的发现。',
                '#FF9800'
            );
        }
    }
    
    showGenericEvent(eventType, levelNumber) {
        this.showEventNotification(
            '🎲 特殊事件',
            `关卡 ${levelNumber}: ${eventType}`,
            '#9C27B0'
        );
    }
    
    adjustLevelBalance(levelNumber, config) {
        // 根据肉鸽进度调整难度
        if (window.roguelikeEnhanced) {
            const runCount = window.roguelikeEnhanced.runCount;
            const difficultyMultiplier = 1 + Math.min(runCount * 0.1, 1.0); // 最多增加100%难度
            
            // 调整敌人属性
            if (window.gameEngine && window.gameEngine.zombies) {
                window.gameEngine.zombies.forEach(zombie => {
                    if (zombie.maxHealth) {
                        zombie.maxHealth *= difficultyMultiplier;
                        zombie.health = zombie.maxHealth;
                    }
                });
            }
        }
    }
    
    setupRoguelikeLoop() {
        // 监听关卡完成事件
        this.originalShowLevelComplete = window.game?.showLevelComplete;
        if (window.game) {
            window.game.showLevelComplete = (levelNumber) => {
                // 触发升级选择
                if (levelNumber < 10 && window.roguelikeSystem) {
                    setTimeout(() => {
                        window.roguelikeSystem.showUpgradeSelection();
                    }, 1500);
                }
                
                // 调用原始方法
                if (this.originalShowLevelComplete) {
                    this.originalShowLevelComplete.call(window.game, levelNumber);
                }
            };
        }
        
        // 监听玩家死亡事件
        this.setupDeathHandling();
    }
    
    setupDeathHandling() {
        if (window.Player && window.Player.prototype.takeDamage) {
            const originalTakeDamage = window.Player.prototype.takeDamage;
            
            window.Player.prototype.takeDamage = function(damage) {
                const wasDead = this.health <= 0;
                const result = originalTakeDamage.call(this, damage);
                
                if (!wasDead && this.health <= 0) {
                    // 玩家刚死亡，触发肉鸽死亡处理
                    setTimeout(() => {
                        if (window.roguelikeEnhanced) {
                            window.roguelikeEnhanced.handlePlayerDeath();
                        }
                    }, 2000); // 延迟2秒显示死亡总结
                }
                
                return result;
            };
        }
    }
    
    enhanceGameEvents() {
        // 增强现有的游戏事件
        this.setupKillRewards();
        this.setupLevelProgression();
    }
    
    setupKillRewards() {
        // 监听僵尸死亡，给予随机奖励
        if (window.Zombie && window.Zombie.prototype.die) {
            const originalDie = window.Zombie.prototype.die;
            
            window.Zombie.prototype.die = function() {
                const result = originalDie.call(this);
                
                // 随机掉落奖励
                if (Math.random() < 0.15) { // 15%概率掉落
                    setTimeout(() => {
                        if (window.equipmentSystem) {
                            const dropType = Math.random() < 0.3 ? 'weapon' : 'item';
                            window.equipmentSystem.spawnEquipmentDrop(this.x, this.y, dropType);
                        }
                    }, 100);
                }
                
                // 更新统计
                if (window.roguelikeEnhanced) {
                    window.roguelikeEnhanced.updateRunStats(1, 0);
                }
                
                return result;
            };
        }
    }
    
    setupLevelProgression() {
        // 设置关卡间的肉鸽循环
        if (window.game && window.game.nextLevel) {
            const originalNextLevel = window.game.nextLevel;
            
            window.game.nextLevel = function() {
                // 记录关卡完成
                if (window.roguelikeEnhanced) {
                    window.roguelikeEnhanced.completeLevel(window.levelManager.currentLevel);
                }
                
                return originalNextLevel.call(this);
            };
        }
    }
    
    updateRoguelikeElements() {
        // 更新动态环境
        if (window.levelManager && window.levelManager.dynamicEnvironment) {
            window.levelManager.dynamicEnvironment.update();
        }
        
        // 更新装备效果
        this.updateEquipmentEffects();
    }
    
    updateEquipmentEffects() {
        // 检查并更新临时装备效果
        const currentTime = Date.now();
        Object.keys(window.equipmentSystem?.equipmentEffects || {}).forEach(effectId => {
            const effect = window.equipmentSystem.equipmentEffects[effectId];
            if (currentTime - effect.startTime > 60000) { // 1分钟后自动清理
                window.equipmentSystem.removeTemporaryEffect(effectId);
            }
        });
    }
    
    setupEventListeners() {
        // 监听游戏初始化
        document.addEventListener('DOMContentLoaded', () => {
            setTimeout(() => {
                this.initialize();
            }, 2000);
        });
    }
    
    // 显示关卡特色提示
    showLevelFeatureHint(config) {
        this.showEventNotification(
            `🎯 关卡特色: ${config.name}`,
            config.description,
            '#2196F3',
            4000
        );
    }
    
    // 显示修饰符
    displayLevelModifiers(modifiers) {
        const modifierText = modifiers.map(m => m.description).join(', ');
        this.showEventNotification(
            '⚡ 关卡修饰符',
            modifierText,
            '#9C27B0',
            6000
        );
    }
    
    // 通用事件通知显示
    showEventNotification(title, message, color = '#4CAF50', duration = 3000) {
        const notification = document.createElement('div');
        notification.className = 'roguelike-notification';
        notification.innerHTML = `
            <div class="notification-content" style="border-color: ${color};">
                <h4 style="color: ${color};">${title}</h4>
                <p>${message}</p>
            </div>
        `;
        
        document.body.appendChild(notification);
        
        // 添加样式
        this.addNotificationStyles();
        
        // 自动移除
        setTimeout(() => {
            if (notification.parentNode) {
                notification.style.animation = 'notificationExit 0.5s ease-out';
                setTimeout(() => {
                    if (notification.parentNode) {
                        document.body.removeChild(notification);
                    }
                }, 500);
            }
        }, duration);
    }
    
    addNotificationStyles() {
        if (document.getElementById('roguelikeNotificationStyles')) return;
        
        const styles = document.createElement('style');
        styles.id = 'roguelikeNotificationStyles';
        styles.textContent = `
            .roguelike-notification {
                position: fixed;
                top: 20px;
                right: 20px;
                z-index: 11000;
                animation: notificationEntry 0.6s ease-out;
                max-width: 350px;
            }
            
            .notification-content {
                background: linear-gradient(135deg, rgba(0, 0, 0, 0.9), rgba(30, 30, 30, 0.9));
                border: 2px solid;
                border-radius: 12px;
                padding: 15px 20px;
                color: white;
                box-shadow: 0 5px 20px rgba(0, 0, 0, 0.3);
                backdrop-filter: blur(5px);
            }
            
            .notification-content h4 {
                margin: 0 0 8px 0;
                font-size: 16px;
                font-weight: bold;
            }
            
            .notification-content p {
                margin: 0;
                font-size: 14px;
                line-height: 1.4;
                opacity: 0.9;
            }
            
            @keyframes notificationEntry {
                0% {
                    opacity: 0;
                    transform: translateX(100px);
                }
                100% {
                    opacity: 1;
                    transform: translateX(0);
                }
            }
            
            @keyframes notificationExit {
                0% {
                    opacity: 1;
                    transform: translateX(0);
                }
                100% {
                    opacity: 0;
                    transform: translateX(100px);
                }
            }
        `;
        
        document.head.appendChild(styles);
    }
}

// 全局实例
window.roguelikeIntegration = new RoguelikeIntegration();

console.log('🎮 肉鸽整合系统已加载');